<template>
  <div>
    <el-row>
      <el-page-header @back="goBack" content="设备列表"> </el-page-header>
    </el-row>
    <el-row justify="start">
      <el-col :span="24">
        <el-form :inline="true" class="device-list-charts">
          <el-form-item label="当前活动数量">
            <span>{{ onlineDeviceCount }}</span>
          </el-form-item>
          <el-form-item label="当前离线设备总数">
            <span>{{ offlineDeviceCount }}</span>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <el-row justify="start">
      <el-col :span="24">
        <el-form :inline="true" :model="deviceSearchForm" class="demo-form-inline">
          <el-form-item label="状态">
            <el-select v-model="deviceSearchForm.deviceState" placeholder="状态">
              <el-option label="全部" value=""></el-option>
              <el-option label="在线" value="online"></el-option>
              <el-option label="离线" value="offline"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="设备编号">
            <el-input v-model="deviceSearchForm.deviceCode" placeholder="设备编号"></el-input>
          </el-form-item>
          <el-form-item label="IP地址">
            <el-input v-model="deviceSearchForm.deviceIp" placeholder="IP地址"></el-input>
          </el-form-item>
          <el-form-item label="设备类型">
            <el-select v-model="deviceSearchForm.deviceType" placeholder="设备类型">
              <el-option label="全部" value=""></el-option>
              <el-option label="人员定位" value="人员定位"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="getDeives">查询</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <template>
          <el-table :data="devicesHandler" stripe style="width: 100%">
            <el-table-column prop="deviceCode" label="设备编号">
            </el-table-column>
            <el-table-column prop="deviceType" label="设备类型">
            </el-table-column>
            <el-table-column prop="deviceState" label="设备状态">
                <template slot-scope="scope">
                    <span v-if="scope.row.deviceState==='online'">
                      <el-tag :type="scope.row.deviceState === 'online' ? 'primary' : 'danger'">在线</el-tag>
                    </span>
                    <span v-if="scope.row.deviceState==='offline'">
                      <el-tag :type="scope.row.deviceState === 'online' ? 'primary' : 'danger'">离线</el-tag>
                    </span>
                </template>
            </el-table-column>
            <el-table-column prop="ip" label="IP"> </el-table-column>
            <el-table-column prop="updateTime" label="更新日期">
            </el-table-column>
            <el-table-column label="操作" width="100" fixed="right">
              <template slot-scope="scope">
                <el-button v-if="scope.row.deviceState==='online'" type="text" size="small" :disabled="scope.row.disableState"
                  @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                <el-button v-if="scope.row.deviceState==='online'" type="text" size="small"
                  @click="handleReboot(scope.$index, scope.row)">重启</el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-col>
    </el-row>
    <el-row type="flex" class="row-bg device-list-pagination" justify="end">
      <el-pagination background layout="prev, pager, next" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[10, 20, 50]"
        :page-size="pageSize" :total="pageTotal" prev-text="上一页" next-text="下一页">
      </el-pagination>
    </el-row>
    <device-edit ref="deviceEditDialog"></device-edit>
  </div>
</template>

<script>
  import mqtt from "mqtt";
  import mqttApi from "@/api/mqtt";
  import { uuid } from "vue-uuid";
  import deviceApi from "@/api/device";
  import DeviceEdit from "./device-edit.vue";
  export default {
    name: "DeviceList",
    provide() {
      return {
        closeEdit: this.closeEdit
      }
    },
    data() {
      return {
        currentPage: 1, //默认显示页面为1
        pageSize: 10, //    每页的数据条数
        pageTotal: 1,
        devices: [],
        onlineDeviceCount: 0,
        offlineDeviceCount: 0,
        deviceSearchForm: {
          deviceState: null,
          deviceCode: null,
          deviceType: null,
          deviceIp: null,
        },
      };
    },
    components: {
      DeviceEdit,
    },
    computed: {
      devicesHandler() {
        // for (let i in this.devices) {
        //   let dev = this.devices[i];
        //   // dev.deviceState = dev.deviceState === "online" ? "在线" : "离线";
        // }
        return this.devices;
      },
    },
    created() { },
    mounted() {
      this.init();
      this.getDeives();
    },
    methods: {
      init() {
        deviceApi.getDeviceStatistics().then((response) => {
          if (response.data) {
            this.onlineDeviceCount = response.data.onlineDevice;
            this.offlineDeviceCount = response.data.offlineDevice;
          }
        });
        mqttApi.getConfig().then((response) => {
          if (response.data) {
            let config = response.data;
            this.mqttInit(config.ip, config.port, config.user, config.password);
          }
        });
      },
      getDeives() {
        let param = {
          page: this.currentPage - 1,
          deviceState: this.deviceSearchForm.deviceState,
          deviceCode: this.deviceSearchForm.deviceCode,
          deviceType: this.deviceSearchForm.deviceType,
          ip: this.deviceSearchForm.deviceIp,
          size: this.pageSize,
        };
        deviceApi.getDevices(param).then((response) => {
          if (response.data) {
            this.devices = response.data.content;
            this.pageTotal = response.data.totalElements - 1;
            this.currentPage = response.data.pageable.pageNumber + 1;
          }
        });
      },
      handleEdit(index, row) {
        this.$refs.deviceEditDialog.resetTab("base");
        this.$refs.deviceEditDialog.show(row);
      },
      handleReboot(index, row) {
        this.$confirm("此操作将重启设备，是否确定重启?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            deviceApi.reboot(row.deviceCode).then(
              (response) => {
                this.$message({
                  message: "重启设备命令已下发。",
                  type: "success",
                });
              },
              (err) => {
                this.$message.error("重启设备失败！" + err);
              }
            );
          })
          .catch(() => { });
      },
      goBack() {
        window.history.back();
      },
      //每页下拉显示数据
      handleSizeChange: function (size) {
        this.pageSize = size;
        this.getDeives();
      },
      //点击第几页
      handleCurrentChange: function (currentPage) {
        this.currentPage = currentPage;
        this.getDeives();
      },
      // 点击修改面板的确定,编辑变灰,收到mqtt后恢复
      closeEdit(deviceCode,flag) {
        for(let i=0;i<this.devices.length;i++){
          if(deviceCode===this.devices[i].deviceCode){
            this.$set( this.devices[i],"disableState",flag);
            break;
          }
        }
      },
      mqttInit(serverIp, serverPort, username, password) {
        let root = this;
        const options = {
          connectTimeout: 40000,
          clientId: "device-list-client-" + uuid.v1(),
          username: username,
          password: password,
          clean: true,
        };
        let mqTTUrl = "ws://" + serverIp + ":" + serverPort + "/mqtt";
        this.client = mqtt.connect(mqTTUrl, options);
        this.client.on("connect", (e) => {
          console.log("连接成功！！！");
          this.client.subscribe("personpositon/+/config", { qos: 0 }, (error) => {
            if (!error) {
              console.log("订阅config成功");
            } else {
              console.log("订阅config失败");
            }
          });
          this.client.subscribe("personpositon/+/timeout", { qos: 1 }, (error) => {
            if (!error) {
              console.log("订阅timeout成功");
            } else {
              console.log("订阅timeout失败");
            }
          });
        });
        // 接收消息处理
        this.client.on("message", (topic, message) => {
          if (topic.indexOf("config") != -1) {
            root.getDeives();
          }
          if (topic.indexOf("timeout") != -1) {
            this.$message({
              message:
                "网络开小差了，请等待一段时间后重试",
              type: "error",
            });
          }
        });
      },
    },
  };
</script>
<style>
  .device-list-charts {
    text-align: left;
    margin-top: 20px;
  }

  .device-list-pagination {
    margin-top: 30px;
  }
</style>